from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse

from goods.models import SKU
from goods.utils import get_breadcrumb


class ListView(View):
    def get(self,request,category_id):
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        # 过滤条件+排序
        skus = SKU.objects.filter(category_id=category_id).order_by(ordering)
        # 分页
        # Paginator: 第一个参数是被分页的查询集；第二个参数是每页几个划分
        paginator = Paginator(skus, page_size)

        # page_skus: 是一个查询集，是分页之后取得的当前页面数据查询集
        try:
            page_skus = paginator.page(page)
        except EmptyPage as e:
            print(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '页面不存在'
            })

        # 构建响应
        data_list = []
        for sku in page_skus:
            data_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        # 分页器对象中属性 num_pages， 总页数
        total_page = paginator.num_pages
        breadcrumb = get_breadcrumb(category_id)

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'list': data_list,
            'count': total_page,
            'breadcrumb': breadcrumb
        })

# 列表页热销排行
class HotGoodsView(View):
    def get(self,request,category_id):
        """提供商品热销排行JSON数据"""
        # 根据销量倒序
        try:
            skus = SKU.objects.filter(category_id=category_id,
                                      is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '获取商品出错'
            })
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'hot_skus': hot_skus
        })

# 全文检索
from haystack.views import SearchView

class MySearchView(SearchView):
    def create_response(self):
        # page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []

        print(context['page'].object_list)

        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数
        return JsonResponse(data_list,safe=False)